import { getArticleList, getNewList } from '@/store/actions/home'
import { RootState } from '@/types/store'
import { useEffect } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import ArticleItem from '../ArticleItem'
import { InfiniteScroll, PullToRefresh } from 'antd-mobile'

import styles from './index.module.scss'
import { useHistory } from 'react-router-dom'

type Props = {
  channelId: number
}

const ArticleList = ({channelId}: Props) => {

  const dispatch = useDispatch();
  useEffect(() => {
    dispatch(getArticleList(Date.now(), channelId))
  }, [dispatch, channelId])

  const history = useHistory()

  const {article} = useSelector((state: RootState) => state.home);
  const {results = [], timestamp} = article[channelId] || {}

  const hasMore = timestamp !== null && results.length <= 100

  const loadMore = async () => {
    await dispatch(getArticleList(timestamp || Date.now(), channelId))
  }

  const onRefresh = async () => {
    await dispatch(getNewList(Date.now(), channelId))
  }

  return (
    <div className={styles.root}>
      {/* 文章列表中的每一项 */}
      <PullToRefresh onRefresh={onRefresh}>
        {
          results.map((article, i) => (
            <div
              key={i}
              className="article-item"
              onClick={() => {
                history.push(`/article/${article.art_id}`)
              }}  
            >
              <ArticleItem article={article}/>
            </div>
          ))
        }
        <InfiniteScroll hasMore={hasMore} loadMore={loadMore}/>
      </PullToRefresh>
    </div>
  )
}

export default ArticleList
